<template>
  <div>
    <div v-if="stage === 'instructions'">
      <motion.div
        :initial="{ opacity: 0, y: 20 }"
        :animate="{ opacity: 1, y: 0 }"
        class="max-w-2xl mx-auto"
      >
        <Card class="bg-white/90 backdrop-blur-sm border-teal-200 shadow-lg">
          <CardHeader class="text-center pb-8">
            <div class="w-16 h-16 bg-gradient-to-br from-teal-600 to-cyan-500 rounded-2xl flex items-center justify-center mx-auto mb-4 shadow-lg">
              <Eye class="w-8 h-8 text-white" />
            </div>
            <CardTitle class="text-2xl text-slate-800">{{ $t('visualPerceptionTest.title') }}</CardTitle>
            <p class="text-slate-600 mt-2">{{ $t('visualPerceptionTest.description') }}</p>
          </CardHeader>

          <CardContent class="space-y-6">
            <div class="bg-gradient-to-r from-teal-50 to-cyan-50 rounded-xl p-6 border border-teal-100">
              <h3 class="font-semibold text-teal-900 mb-4 flex items-center gap-2">
                <Star class="w-5 h-5" />
                {{ $t('visualPerceptionTest.instructions.title') }}
              </h3>
              <div class="space-y-3 text-slate-700">
                <div class="flex gap-3">
                  <span class="w-6 h-6 bg-teal-600 text-white rounded-full flex items-center justify-center text-sm font-semibold flex-shrink-0 mt-0.5">1</span>
                  <p>{{ $t('visualPerceptionTest.instructions.step1') }}</p>
                </div>
                <div class="flex gap-3">
                  <span class="w-6 h-6 bg-teal-600 text-white rounded-full flex items-center justify-center text-sm font-semibold flex-shrink-0 mt-0.5">2</span>
                  <p>{{ $t('visualPerceptionTest.instructions.step2') }}</p>
                </div>
                <div class="flex gap-3">
                  <span class="w-6 h-6 bg-teal-600 text-white rounded-full flex items-center justify-center text-sm font-semibold flex-shrink-0 mt-0.5">3</span>
                  <p>{{ $t('visualPerceptionTest.instructions.step3') }}</p>
                </div>
                <div class="flex gap-3">
                  <span class="w-6 h-6 bg-teal-600 text-white rounded-full flex items-center justify-center text-sm font-semibold flex-shrink-0 mt-0.5">4</span>
                  <p>{{ $t('visualPerceptionTest.instructions.step4') }}</p>
                </div>
              </div>
            </div>

            <div class="grid md:grid-cols-2 gap-4">
              <div class="bg-gradient-to-br from-blue-50 to-blue-100 rounded-xl p-4 border border-blue-200">
                <h4 class="font-semibold text-blue-800 mb-2 flex items-center gap-2">
                  <Target class="w-4 h-4" />
                  {{ $t('visualPerceptionTest.features.targetDetection') }}
                </h4>
                <p class="text-sm text-blue-700">{{ $t('visualPerceptionTest.features.targetDetectionDesc') }}</p>
              </div>
              <div class="bg-gradient-to-br from-purple-50 to-purple-100 rounded-xl p-4 border border-purple-200">
                <h4 class="font-semibold text-purple-800 mb-2 flex items-center gap-2">
                  <Zap class="w-4 h-4" />
                  {{ $t('visualPerceptionTest.features.fastRecognition') }}
                </h4>
                <p class="text-sm text-purple-700">{{ $t('visualPerceptionTest.features.fastRecognitionDesc') }}</p>
              </div>
            </div>

            <div class="grid md:grid-cols-3 gap-4">
              <div class="text-center p-4 bg-gradient-to-br from-teal-50 to-teal-100 rounded-xl border border-teal-200">
                <div class="text-2xl font-bold text-teal-600 mb-1">8</div>
                <div class="text-sm text-teal-700">{{ $t('visualPerceptionTest.summary.taskTypes') }}</div>
              </div>
              <div class="text-center p-4 bg-gradient-to-br from-cyan-50 to-cyan-100 rounded-xl border border-cyan-200">
                <div class="text-2xl font-bold text-cyan-600 mb-1">15</div>
                <div class="text-sm text-cyan-700">{{ $t('visualPerceptionTest.summary.dynamicTasks') }}</div>
              </div>
              <div class="text-center p-4 bg-gradient-to-br from-teal-50 to-cyan-50 rounded-xl border border-teal-200">
                <div class="text-2xl font-bold text-slate-600 mb-1">{{ $t('visualPerceptionTest.summary.timed') }}</div>
                <div class="text-sm text-slate-700">{{ $t('visualPerceptionTest.summary.challenge') }}</div>
              </div>
            </div>

            <Button
              @click="handleStartTest"
              class="w-full bg-gradient-to-r from-teal-600 to-cyan-500 hover:from-teal-700 hover:to-cyan-600 text-white py-3 text-lg font-semibold shadow-lg hover:shadow-xl transition-all duration-200"
              size="lg"
            >
              {{ $t('visualPerceptionTest.startTest') }}
            </Button>
          </CardContent>
        </Card>
      </motion.div>
    </div>

    <div v-else-if="stage === 'test' && tasks.length > 0">
      <motion.div
        :initial="{ opacity: 0, scale: 0.95 }"
        :animate="{ opacity: 1, scale: 1 }"
        class="max-w-4xl mx-auto space-y-6"
      >
        <!-- 顶部状态栏 -->
        <div class="flex flex-col sm:flex-row gap-4 items-center justify-between">
          <div class="flex items-center gap-4">
            <Badge variant="outline" class="bg-teal-100 text-teal-700 border-teal-300">
              {{ $t('visualPerceptionTest.task', { currentTask: currentTask + 1, totalTasks: tasks.length }) }}
            </Badge>
            <Badge variant="outline" :class="[
              task.type === 'target_detection' ? 'bg-blue-100 text-blue-700 border-blue-300' :
              task.type === 'color_discrimination' ? 'bg-green-100 text-green-700 border-green-300' :
              task.type === 'size_comparison' ? 'bg-purple-100 text-purple-700 border-purple-300' :
              task.type === 'spatial_memory' ? 'bg-orange-100 text-orange-700 border-orange-300' :
              task.type === 'shape_recognition' ? 'bg-pink-100 text-pink-700 border-pink-300' :
              'bg-indigo-100 text-indigo-700 border-indigo-300'
            ]">
              {{ $t(`visualPerceptionTest.taskTypes.${task.type}`) }}
            </Badge>
            <div class="flex items-center gap-2 text-slate-600">
              <Trophy class="w-4 h-4" />
              <span class="font-semibold">{{ score }}</span>
            </div>
          </div>

          <div class="flex items-center gap-2">
            <Clock class="w-4 h-4 text-slate-500" />
            <span :class="`font-mono text-lg font-bold ${timeLeft <= 5 ? 'text-red-500' : 'text-slate-700'}`">
              {{ $t('visualPerceptionTest.timeLeft', { timeLeft }) }}
            </span>
          </div>
        </div>

        <Progress :model-value="progress" class="h-2" />

        <!-- 任务指令 -->
        <Card class="bg-gradient-to-r from-slate-50 to-gray-50 border-slate-200">
          <CardHeader>
            <CardTitle class="text-lg text-slate-800 text-center">
              {{ task.instruction }}
            </CardTitle>
          </CardHeader>
        </Card>

        <!-- 画布区域 -->
        <Card class="bg-white/90 backdrop-blur-sm border-teal-200 shadow-lg">
          <CardContent class="p-6">
            <div class="flex flex-col items-center gap-4">
              <canvas
                ref="canvas"
                :width="CANVAS_WIDTH"
                :height="CANVAS_HEIGHT"
                @click="handleCanvasClick"
                class="border-2 border-slate-300 rounded-lg cursor-crosshair hover:border-teal-400 transition-colors"
                style="max-width: 100%; height: auto"
              />

              <div class="flex gap-4">
                <div class="text-sm text-slate-600">
                  {{ $t('visualPerceptionTest.selected', { selectedCount: selectedElements.length, targetCount: task.targets.length }) }}
                </div>

                <Button
                  @click="handleSubmit"
                  class="bg-gradient-to-r from-teal-600 to-cyan-500 hover:from-teal-700 hover:to-cyan-600 text-white px-6"
                >
                  {{ $t('visualPerceptionTest.submit') }}
                </Button>
              </div>
            </div>
          </CardContent>
        </Card>

        <!-- 反馈弹窗 -->
        <AnimatePresence>
          <motion.div
            v-if="showFeedback"
            :initial="{ opacity: 0, y: -20 }"
            :animate="{ opacity: 1, y: 0 }"
            :exit="{ opacity: 0, y: -20 }"
            class="fixed top-20 left-1/2 transform -translate-x-1/2 z-50"
          >
            <Card :class="`border-0 shadow-lg ${
              feedbackCorrect
                ? 'bg-green-500 text-white'
                : 'bg-red-500 text-white'
            }`">
              <CardContent class="py-3 px-6">
                <div class="text-center font-semibold">
                  {{ feedbackCorrect ? $t('visualPerceptionTest.feedback.correct') : $t('visualPerceptionTest.feedback.incorrect') }}
                </div>
              </CardContent>
            </Card>
          </motion.div>
        </AnimatePresence>
      </motion.div>
    </div>

    <div v-else-if="stage === 'results'">
      <motion.div
        :initial="{ opacity: 0, scale: 0.95 }"
        :animate="{ opacity: 1, scale: 1 }"
        class="max-w-2xl mx-auto"
      >
        <Card class="bg-white/90 backdrop-blur-sm border-teal-200 shadow-xl">
          <CardHeader class="text-center pb-6">
            <motion.div
              :initial="{ scale: 0 }"
              :animate="{ scale: 1 }"
              :transition="{ delay: 0.2, type: 'spring', stiffness: 200 }"
              class="w-20 h-20 bg-gradient-to-br from-teal-600 to-cyan-500 rounded-2xl flex items-center justify-center mx-auto mb-4 shadow-lg"
            >
              <Trophy class="w-10 h-10 text-white" />
            </motion.div>

            <CardTitle class="text-3xl text-slate-800 mb-2">{{ $t('visualPerceptionTest.results.title') }}</CardTitle>
            <div class="text-6xl font-bold bg-gradient-to-r from-teal-600 to-cyan-500 bg-clip-text text-transparent">
              {{ accuracy }}
            </div>
            <p class="text-slate-600">{{ $t('visualPerceptionTest.results.accuracy') }}</p>
          </CardHeader>

          <CardContent class="space-y-6">
            <div class="grid grid-cols-2 gap-4">
              <div class="text-center p-4 bg-gradient-to-br from-teal-50 to-teal-100 rounded-xl border border-teal-200">
                <div class="text-2xl font-bold text-teal-600 mb-1">{{ correctAnswers }}/{{ totalTasks }}</div>
                <div class="text-sm text-teal-700">{{ $t('visualPerceptionTest.results.correctAnswers') }}</div>
              </div>
              <div class="text-center p-4 bg-gradient-to-br from-cyan-50 to-cyan-100 rounded-xl border border-cyan-200">
                <div class="text-2xl font-bold text-cyan-600 mb-1">{{ Math.round(averageReactionTime/1000) }}s</div>
                <div class="text-sm text-cyan-700">{{ $t('visualPerceptionTest.results.averageReaction') }}</div>
              </div>
            </div>

            <Button
              @click="handleComplete"
              class="w-full bg-gradient-to-r from-teal-600 to-cyan-500 hover:from-teal-700 hover:to-cyan-600 text-white py-3 text-lg font-semibold shadow-lg hover:shadow-xl transition-all duration-200"
              size="lg"
            >
              {{ $t('visualPerceptionTest.results.viewDetails') }}
            </Button>
          </CardContent>
        </Card>
      </motion.div>
    </div>
  </div>
</template>

<script setup>
import { Eye, Clock, Trophy, Star, Target, Zap } from 'lucide-vue-next'
import { motion, AnimatePresence } from 'motion-v'
import { useI18n } from 'vue-i18n'
import { ref, computed, onMounted, onUnmounted, watch, nextTick } from 'vue'

const { t } = useI18n()

const props = defineProps({
  onComplete: {
    type: Function,
    required: true
  }
})

const stage = ref('instructions')
const currentTask = ref(0)
const tasks = ref([])
const selectedElements = ref([])
const responses = ref([])
const timeLeft = ref(0)
const taskStartTime = ref(0)
const startTime = ref(0)
const score = ref(0)
const showFeedback = ref(false)
const feedbackCorrect = ref(false)
const canvas = ref(null)
const timer = ref(null)

const TOTAL_TASKS = 15
const CANVAS_WIDTH = 600
const CANVAS_HEIGHT = 400

// 颜色调色板
const COLORS = [
  '#ef4444', '#f97316', '#f59e0b', '#eab308', '#84cc16',
  '#22c55e', '#10b981', '#14b8a6', '#06b6d4', '#0ea5e9',
  '#3b82f6', '#6366f1', '#8b5cf6', '#a855f7', '#d946ef',
  '#ec4899', '#f43f5e'
]

const task = computed(() => tasks.value[currentTask.value] || {})
const progress = computed(() => (currentTask.value / tasks.value.length) * 100)
const totalTasks = computed(() => tasks.value.length)
const correctAnswers = computed(() => score.value)
const accuracy = computed(() => Math.round((correctAnswers.value / totalTasks.value) * 100))
const averageReactionTime = computed(() => responses.value.reduce((sum, r) => sum + r.time, 0) / responses.value.length)

// 生成随机视觉元素
const generateRandomElement = (id, isTarget = false) => {
  const shapes = ['circle', 'square', 'triangle', 'diamond', 'star', 'hexagon']
  const sizes = ['small', 'medium', 'large']
  const sizeMap = { small: 20, medium: 30, large: 40 }

  const shape = shapes[Math.floor(Math.random() * shapes.length)]
  const size = sizes[Math.floor(Math.random() * sizes.length)]
  const actualSize = sizeMap[size]

  return {
    id,
    x: Math.random() * (CANVAS_WIDTH - actualSize * 2) + actualSize,
    y: Math.random() * (CANVAS_HEIGHT - actualSize * 2) + actualSize,
    width: actualSize,
    height: actualSize,
    color: COLORS[Math.floor(Math.random() * COLORS.length)],
    shape,
    rotation: Math.random() * 360,
    opacity: 0.8 + Math.random() * 0.2,
    isTarget,
    size
  }
}

// 生成各种任务类型的函数 (generateTargetDetectionTask, generateColorDiscriminationTask等)
// 与React版本相同，只是去掉了类型注解
// ...

// 生成测试任务

const generateTargetDetectionTask = (id)  => {
  const targetColor = COLORS[Math.floor(Math.random() * COLORS.length)];
  const targetShape = ['circle', 'square', 'triangle'][Math.floor(Math.random() * 3)];

  const elements= [];
  const targets= [];
  const numElements = 12 + Math.floor(Math.random() * 8);
  const numTargets = 2 + Math.floor(Math.random() * 3);

  // 生成目标元素
  for (let i = 0; i < numTargets; i++) {
    const element = generateRandomElement(i, true);
    element.color = targetColor;
    element.shape = targetShape
    elements.push(element);
    targets.push(i);
  }

  // 生成干扰元素
  for (let i = numTargets; i < numElements; i++) {
    const element = generateRandomElement(i);
    // 确保不是目标
    if (element.color === targetColor && element.shape === targetShape) {
      element.color = COLORS.filter(c => c !== targetColor)[Math.floor(Math.random() * (COLORS.length - 1))];
    }
    elements.push(element);
  }

  return {
    id,
    type: 'target_detection',
    instruction: t('visualPerceptionTest.instructionsContent.target_detection', { shape: t(`visualPerceptionTest.shapes.${targetShape}`), color: t(`visualPerceptionTest.colors.${targetColor === '#ef4444' ? 'red' : targetColor === '#3b82f6' ? 'blue' : targetColor === '#22c55e' ? 'green' : 'specified'}`) }),
    elements,
    targets,
    timeLimit: 15,
    difficulty: numTargets > 3 ? 'hard' : numTargets > 2 ? 'medium' : 'easy',
    minTargets: numTargets,
    maxTargets: numTargets
  };
};

const generateColorDiscriminationTask = (id)  => {
  const baseColor = COLORS[Math.floor(Math.random() * COLORS.length)];
  const elements= [];
  const targets = [];
  const numElements = 8 + Math.floor(Math.random() * 4);

  // 生成一个颜色略有不同的目标
  for (let i = 0; i < numElements; i++) {
    const element = generateRandomElement(i);
    element.shape = 'circle'; // 统一形状，专注颜色

    if (i === 0) { // 第一个是目标
      element.color = baseColor;
      element.isTarget = true;
      targets.push(i);
    } else {
      // 其他元素使用相近但不同的颜色
      const similarColors = COLORS.filter(c => c !== baseColor);
      element.color = similarColors[Math.floor(Math.random() * similarColors.length)];
    }

    elements.push(element);
  }

  return {
    id,
    type: 'color_discrimination',
    instruction: t('visualPerceptionTest.instructionsContent.color_discrimination'),
    elements,
    targets,
    timeLimit: 12,
    difficulty: 'medium',
    minTargets: 1,
    maxTargets: 1
  };
};

const generateSizeComparisonTask = (id)  => {
  const elements= [];
  const targets= [];
  const shapes = ['circle', 'square'];
  const shape = shapes[Math.floor(Math.random() * shapes.length)]
  const color = COLORS[Math.floor(Math.random() * COLORS.length)];

  // 生成不同大小的元素
  const sizes = [15, 20, 25, 30, 35, 40];
  const targetSize = Math.max(...sizes);

  for (let i = 0; i < 6; i++) {
    const element = generateRandomElement(i);
    element.shape = shape;
    element.color = color;
    element.width = sizes[i];
    element.height = sizes[i];

    if (sizes[i] === targetSize) {
      element.isTarget = true;
      targets.push(i);
    }

    elements.push(element);
  }

  return {
    id,
    type: 'size_comparison',
    instruction: t('visualPerceptionTest.instructionsContent.size_comparison'),
    elements,
    targets,
    timeLimit: 10,
    difficulty: 'easy',
    minTargets: 1,
    maxTargets: 1
  };
};

const generateSpatialMemoryTask = (id) => {
  const elements= [];
  const targets = [];
  const numElements = 6 + Math.floor(Math.random() * 4);

  // 生成随机位置的元素
  for (let i = 0; i < numElements; i++) {
    const element = generateRandomElement(i);
    element.color = COLORS[0]; // 统一颜色
    element.shape = 'circle'; // 统一形状

    // 随机选择一些作为目标（记忆位置）
    if (Math.random() > 0.7 && targets.length < 3) {
      element.isTarget = true;
      targets.push(i);
    }

    elements.push(element);
  }

  // 确保至少有一个目标
  if (targets.length === 0) {
    elements[0].isTarget = true;
    targets.push(0);
  }

  return {
    id,
    type: 'spatial_memory',
    instruction: t('visualPerceptionTest.instructionsContent.spatial_memory'),
    elements,
    targets,
    timeLimit: 20,
    difficulty: targets.length > 2 ? 'hard' : 'medium',
    minTargets: targets.length,
    maxTargets: targets.length
  };
};

const generateShapeRecognitionTask = (id) => {
  const targetShape = ['star', 'hexagon', 'diamond'][Math.floor(Math.random() * 3)]
  const elements = [];
  const targets= [];
  const numElements = 10 + Math.floor(Math.random() * 5);

  for (let i = 0; i < numElements; i++) {
    const element = generateRandomElement(i);

    if (i < 2) { // 前两个是目标
      element.shape = targetShape;
      element.isTarget = true;
      targets.push(i);
    } else {
      // 确保不是目标形状
      const otherShapes = ['circle', 'square', 'triangle'].filter(s => s !== targetShape);
      element.shape = otherShapes[Math.floor(Math.random() * otherShapes.length)]
    }

    elements.push(element);
  }

  return {
    id,
    type: 'shape_recognition',
    instruction: t('visualPerceptionTest.instructionsContent.shape_recognition', { shape: t(`visualPerceptionTest.shapes.${targetShape}`) }),
    elements,
    targets,
    timeLimit: 15,
    difficulty: 'medium',
    minTargets: 2,
    maxTargets: 2
  };
};

const generatePatternMatchingTask = (id) => {
  const elements = [];
  const targets = [];

  // 创建一个简单的对称模式
  const baseElements = 4;
  for (let i = 0; i < baseElements; i++) {
    const element = generateRandomElement(i);
    element.x = 150 + i * 60;
    element.y = 200;
    elements.push(element);

    // 创建对称元素
    const symmetric = { ...element };
    symmetric.id = baseElements + i;
    symmetric.x = CANVAS_WIDTH - element.x;
    symmetric.isTarget = true;
    elements.push(symmetric);
    targets.push(baseElements + i);
  }

  return {
    id,
    type: 'pattern_matching',
    instruction: t('visualPerceptionTest.instructionsContent.pattern_matching'),
    elements,
    targets,
    timeLimit: 18,
    difficulty: 'hard',
    minTargets: baseElements,
    maxTargets: baseElements
  };
};

// 绘制图形到Canvas
const drawElement = (ctx, element) => {
  ctx.save()
  ctx.translate(element.x, element.y)
  ctx.rotate((element.rotation * Math.PI) / 180)
  ctx.globalAlpha = element.opacity
  ctx.fillStyle = element.color
  ctx.strokeStyle = element.isTarget ? '#000000' : element.color
  ctx.lineWidth = selectedElements.value.includes(element.id) ? 3 : 1

  const size = element.width

  switch (element.shape) {
    case 'circle':
      ctx.beginPath()
      ctx.arc(0, 0, size / 2, 0, 2 * Math.PI)
      ctx.fill()
      if (selectedElements.value.includes(element.id)) ctx.stroke()
      break

    case 'square':
      ctx.fillRect(-size / 2, -size / 2, size, size)
      if (selectedElements.value.includes(element.id)) {
        ctx.strokeRect(-size / 2, -size / 2, size, size)
      }
      break

    case 'triangle':
      ctx.beginPath()
      ctx.moveTo(0, -size / 2)
      ctx.lineTo(-size / 2, size / 2)
      ctx.lineTo(size / 2, size / 2)
      ctx.closePath()
      ctx.fill()
      if (selectedElements.value.includes(element.id)) ctx.stroke()
      break

    case 'diamond':
      ctx.beginPath()
      ctx.moveTo(0, -size / 2)
      ctx.lineTo(size / 2, 0)
      ctx.lineTo(0, size / 2)
      ctx.lineTo(-size / 2, 0)
      ctx.closePath()
      ctx.fill()
      if (selectedElements.value.includes(element.id)) ctx.stroke()
      break

    case 'star':
      const spikes = 5
      const outerRadius = size / 2
      const innerRadius = outerRadius * 0.4

      ctx.beginPath()
      for (let i = 0; i < spikes * 2; i++) {
        const radius = i % 2 === 0 ? outerRadius : innerRadius
        const angle = (i * Math.PI) / spikes
        const x = Math.cos(angle) * radius
        const y = Math.sin(angle) * radius

        if (i === 0) ctx.moveTo(x, y)
        else ctx.lineTo(x, y)
      }
      ctx.closePath()
      ctx.fill()
      if (selectedElements.value.includes(element.id)) ctx.stroke()
      break

    case 'hexagon':
      ctx.beginPath()
      for (let i = 0; i < 6; i++) {
        const angle = (i * Math.PI) / 3
        const x = Math.cos(angle) * (size / 2)
        const y = Math.sin(angle) * (size / 2)

        if (i === 0) ctx.moveTo(x, y)
        else ctx.lineTo(x, y)
      }
      ctx.closePath()
      ctx.fill()
      if (selectedElements.value.includes(element.id)) ctx.stroke()
      break
  }

  ctx.restore()
}

// 绘制Canvas
const drawCanvas = () => {
  if (!canvas.value || tasks.value.length === 0) return

  const ctx = canvas.value.getContext('2d')
  if (!ctx) return

  // 清空画布
  ctx.clearRect(0, 0, CANVAS_WIDTH, CANVAS_HEIGHT)

  // 绘制背景
  ctx.fillStyle = '#f8fafc'
  ctx.fillRect(0, 0, CANVAS_WIDTH, CANVAS_HEIGHT)

  // 绘制边框
  ctx.strokeStyle = '#e2e8f0'
  ctx.lineWidth = 2
  ctx.strokeRect(0, 0, CANVAS_WIDTH, CANVAS_HEIGHT)

  // 绘制元素
  const current = tasks.value[currentTask.value]
  current?.elements?.forEach(element => {
    drawElement(ctx, element)
  })
}

// 处理Canvas点击
const handleCanvasClick = (event) => {
  if (!canvas.value || tasks.value.length === 0) return

  const rect = canvas.value.getBoundingClientRect()
  const x = event.clientX - rect.left
  const y = event.clientY - rect.top

  const current = tasks.value[currentTask.value]

  // 检查点击的元素
  for (const element of current.elements) {
    const dx = x - element.x
    const dy = y - element.y
    const distance = Math.sqrt(dx * dx + dy * dy)

    if (distance <= element.width / 2 + 5) { // 增加一些点击容错
      handleElementClick(element.id)
      break
    }
  }
}

const handleElementClick = (elementId) => {
  selectedElements.value = selectedElements.value.includes(elementId)
    ? selectedElements.value.filter(id => id !== elementId)
    : [...selectedElements.value, elementId]
}

const startTimer = () => {
  stopTimer()
  timeLeft.value = tasks.value[currentTask.value]?.timeLimit || 15 // 确保有默认值
  timer.value = setInterval(() => {
    timeLeft.value -= 1
    if (timeLeft.value <= 0) {
      handleSubmit()
    }
  }, 1000)
}

const stopTimer = () => {
  if (timer.value) {
    clearInterval(timer.value)
    timer.value = null
  }
}

const handleSubmit = () => {
  stopTimer() // 立即停止计时器
  if (tasks.value.length === 0 || !tasks.value[currentTask.value]) return

  const current = tasks.value[currentTask.value]
  const reactionTime = Date.now() - taskStartTime.value

  // 计算准确率
  const correctSelections = selectedElements.value.filter(id => current.targets.includes(id))
  const incorrectSelections = selectedElements.value.filter(id => !current.targets.includes(id))

  const isCorrect = correctSelections.length === current.targets.length && incorrectSelections.length === 0

  responses.value = [...responses.value, {
    correct: isCorrect,
    time: reactionTime,
    accuracy: current.targets.length > 0 ? (correctSelections.length / current.targets.length) * 100 : (isCorrect ? 100 : 0)
  }]

  if (isCorrect) {
    score.value++
  }

  // 显示反馈
  feedbackCorrect.value = isCorrect
  showFeedback.value = true

  setTimeout(() => {
    showFeedback.value = false
    selectedElements.value = []

    if (currentTask.value < tasks.value.length - 1) {
      currentTask.value++
      nextTick(() => {
        const nextTask = tasks.value[currentTask.value]
        if (nextTask) {
          timeLeft.value = nextTask.timeLimit
          taskStartTime.value = Date.now()
          startTimer()
        } else {
          stage.value = 'results'
        }
      })
    } else {
      stage.value = 'results'
    }
  }, 1500)
}
const generateTasks = () => {
  const tasks  = [];
  let taskId = 1;

  // 目标检测任务 (4道)
  for (let i = 0; i < 4; i++) {
    tasks.push(generateTargetDetectionTask(taskId++));
  }

  // 颜色辨别任务 (3道)
  for (let i = 0; i < 3; i++) {
    tasks.push(generateColorDiscriminationTask(taskId++));
  }

  // 大小比较任务 (3道)
  for (let i = 0; i < 3; i++) {
    tasks.push(generateSizeComparisonTask(taskId++));
  }

  // 空间记忆任务 (2道)
  for (let i = 0; i < 2; i++) {
    tasks.push(generateSpatialMemoryTask(taskId++));
  }

  // 形状识别任务 (2道)
  for (let i = 0; i < 2; i++) {
    tasks.push(generateShapeRecognitionTask(taskId++));
  }

  // 图案匹配任务 (1道)
  tasks.push(generatePatternMatchingTask(taskId++));

  return tasks.sort(() => Math.random() - 0.5);
};


const handleStartTest = () => {
  tasks.value = generateTasks()
  currentTask.value = 0
  selectedElements.value = []
  responses.value = []
  score.value = 0

  if (tasks.value.length > 0) {
    timeLeft.value = tasks.value[0].timeLimit
    startTime.value = Date.now()
    taskStartTime.value = Date.now()
    stage.value = 'test'

    nextTick(() => {
      drawCanvas()
      startTimer()
    })
  } else {
    // 如果没有生成任务，直接显示结果
    stage.value = 'results'
  }
}

const handleComplete = () => {
  const timeUsed = Math.round((Date.now() - startTime.value) / 1000)

  // 按任务类型统计
  const typeStats = {}

  tasks.value.forEach((task, index) => {
    const type = task.type
    if (!typeStats[type]) {
      typeStats[type] = { correct: 0, total: 0, avgTime: 0 }
    }
    typeStats[type].total++
    if (responses.value[index]?.correct) {
      typeStats[type].correct++
    }
    typeStats[type].avgTime += responses.value[index]?.time || 0
  })

  // 计算平均时间
  Object.keys(typeStats).forEach(type => {
    typeStats[type].avgTime = typeStats[type].avgTime / typeStats[type].total
  })

  const result = {
    id: Date.now().toString(),
    testType: 'visual',
    score: accuracy.value,
    completedAt: new Date(),
    duration: timeUsed,
    details: {
      totalTasks: totalTasks.value,
      correctAnswers: correctAnswers.value,
      accuracy: accuracy.value,
      averageReactionTime: Math.round(averageReactionTime.value),
      averageAccuracy: Math.round(responses.value.reduce((sum, r) => sum + r.accuracy, 0) / responses.value.length),
      typeBreakdown: Object.entries(typeStats).map(([type, stats]) => ({
        type: t(`visualPerceptionTest.taskTypes.${type}`),
        accuracy: stats.total > 0 ? Math.round((stats.correct / stats.total) * 100) : 0,
        correct: stats.correct,
        total: stats.total,
        avgReactionTime: Math.round(stats.avgTime)
      })),
      tasksGenerated: tasks.value.map(t => ({ type: t.type, difficulty: t.difficulty }))
    }
  }

  props.onComplete(result)
}

// 监听变化重新绘制Canvas
watch([tasks, currentTask, selectedElements, stage], () => {
  drawCanvas()
})

onMounted(() => {
  drawCanvas()
})

// 组件卸载时清理定时器
onUnmounted(stopTimer)
</script>